package com.tjmntv.tj.myapplication.demo6

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import com.tjmntv.tj.myapplication.R
import kotlinx.android.synthetic.main.activity_kotlin_demo6.*

class KotlinDemo6 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_demo6)

        buttonStartService.setOnClickListener {
            Intent(this, MyService::class.java).also {
                startService(it)
            }
        }

        buttonStartActivity.setOnClickListener {
            Intent(this, KotlinDemoAty6_2::class.java).also {
                startActivity(it)
            }
        }

        buttonBindService.setOnClickListener {
            val bindIntent = Intent(this, MyService::class.java)
            val serviceConnection = object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    // TODO("Not yet implemented")
                    (service as MyService.MyBinder).service.numberLiveData.observe(this@KotlinDemo6, Observer {
                        textView2.text = "$it"
                    })
                }

                override fun onServiceDisconnected(name: ComponentName?) {
                    // TODO("Not yet implemented")
                }
            }
            startService(bindIntent)
            bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }
}